package com.stanwind.netty.core.protocol.codc;

import com.stanwind.netty.constant.ServerSetting;
import com.stanwind.netty.core.protocol.model.Response;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * 响应解码器
 *
 * @author westwind
 *         FrameDecoder协助解决粘包、分包问题
 */
public class ResponseDecoder extends FrameDecoder {
    /**
     * 数据包基础长度
     */
    public static int BASE_LENGTH = 4 + 4 + 2 + 2;

    //[4D 5A 00 00] [00 00 00 00] [LENGTH] [COMMAND] [DATA]
    @Override
    protected Object decode(ChannelHandlerContext context, Channel channel,
                            ChannelBuffer buffer) throws Exception {

        //可读长度必须大于基本长度
        if (buffer.readableBytes() >= BASE_LENGTH) {
            //记录包头开始的index  0 <= readIndex <= writeIndex
            int beginReader = buffer.readerIndex();

            //读到包头
            while (true) {
                if (buffer.readInt() == ServerSetting.FLAG) {
                    break;
                }
            }

            //读time
            int time = buffer.readInt();
            //读length 减cmd
            int length = buffer.readShort() - 2;
            //读cmd
            short cmd = buffer.readShort();
            //读data
            if (buffer.readableBytes() < length) {
                //还原读指针 下次调用时再从包头开始
                buffer.readerIndex(beginReader);
                //data数据不完整
                return null;
            }
            byte[] data = new byte[length];
            buffer.readBytes(length);

            //新建相应对象
            Response response = new Response();
            response.setTime(time);
            response.setCmd(cmd);
            response.setData(data);

            //往下传递
            return response;
        }

        //数据包不完整 等待后面的包
        return null;


    }


}
